package com.pro.springbootshop.service.impl;

import com.pro.springbootshop.entity.*;
import com.pro.springbootshop.entityExtend.OrderReturn;
import com.pro.springbootshop.entityExtend.SearchOrder;
import com.pro.springbootshop.mapper.CartMapper;
import com.pro.springbootshop.mapper.HistoryOrderMapper;
import com.pro.springbootshop.mapper.OrderMapper;
import com.pro.springbootshop.mapper.WaresMapper;
import com.pro.springbootshop.mapper.ExtendOrdersMapper;
import com.pro.springbootshop.service.OrdersService;
import com.pro.springbootshop.util.SellerTokenUtil;
import com.pro.springbootshop.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    TokenUtil tokenUtil;
    public OrderMapper orderMapper;
    @Autowired
    public void setUserMapper (OrderMapper orderMapper) {
        this.orderMapper = orderMapper;
    }
    public ExtendOrdersMapper extendOrdersMapper;
    @Autowired
    public void setUserMapper (ExtendOrdersMapper extendOrdersMapper) {
        this.extendOrdersMapper = extendOrdersMapper;
    }
    public CartMapper cartMapper;
    @Autowired
    public void setUserMapper (CartMapper cartMapper) {
        this.cartMapper = cartMapper;
    }
    public HistoryOrderMapper historyOrderMapper;
    @Autowired
    public void setUserMapper (HistoryOrderMapper historyOrderMapper) {
        this.historyOrderMapper= historyOrderMapper;
    }
    public WaresMapper waresMapper;
    @Autowired
    public void setUserMapper (WaresMapper waresMapper) {
        this.waresMapper = waresMapper;
    }
    @Autowired
    SellerTokenUtil sellerTokenUtil;

    @Override
    public OrderReturn getOrderList(Integer page, Integer limit, String token) {
        Map<String,String> buyerMap=tokenUtil.parseToken(token);
        String buyerId=buyerMap.get("buyerId");
        int pageNo=(page-1)*limit;
        int total=orderMapper.getOrderListCount(buyerId,"admin","admin").size();
        List<Orders> ordersList= orderMapper.getOrderList(buyerId,pageNo,limit,"admin","admin");
        for(Orders o:ordersList){
            o.getWares().setPictureList(o.getWares().getWaresPicture().split(";"));
        }
        return new OrderReturn(ordersList,total);
    }

    @Override
    public String deleteOrder(Integer orderId) {
        Orders order=orderMapper.selectById(orderId);
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        if(order.getOrderState()<=5){
            int i=orderMapper.deleteById(orderId);
            if(i>0){
                HistoryOrder historyOrder=new HistoryOrder();
                historyOrder.setBuyerId(order.getBuyerId());
                historyOrder.setHistoryOrderState(2);
                if(order.getOrderState()==2) {
                    int extendOrdersId = extendOrdersMapper.getExtendOrdersId(orderId);
                    extendOrdersMapper.deleteById(extendOrdersId);
                }
                historyOrder.setSellerId(order.getSellerId());
                historyOrder.setWaresId(order.getWaresId());
                historyOrder.setWaresNumber(order.getWaresNumber());
                historyOrder.setFinishTime(formatter.format(date));
                historyOrderMapper.insert(historyOrder);
                return "删除成功";
            }else{
                return "删除失败";
            }
        }else{
            return "无法删除";
        }
    }

    @Override
    public String insertOrder(String address,String token,Integer payment) {
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String,String> buyerMap=tokenUtil.parseToken(token);
        String buyerId=buyerMap.get("buyerId");
        List<Cart> cartList=cartMapper.selectCartShop(buyerId);
        Orders order=new Orders();
        ExtendOrders extendOrders=new ExtendOrders();
        if(extendOrdersMapper.getMaxOrdersId()!=null){
            extendOrders.setOrdersId(extendOrdersMapper.getMaxOrdersId()+1);
        }else {
            extendOrders.setOrdersId(1);
        }
        int i=0;
        for(Cart cart:cartList){
            if(cart.getCartState()==1){
                if(cart.getWaresNumber()==0){
                    cartMapper.deleteById(cart.getCartId());
                }else{
                    order.setWaresId(cart.getWaresId());
                    order.setBuyerId(buyerId);
                    order.setWaresNumber(cart.getWaresNumber());
                    order.setOrderTime(formatter.format(date));
                    order.setOrderState(payment);
                    order.setSellerId(waresMapper.getSellerIdByWares(cart.getWaresId()));
                    if(!address.equals("")){
                        order.setAddress(address);
                    }
                    i=orderMapper.insert(order);
                    extendOrders.setOrderId(order.getOrderId());
                    extendOrdersMapper.insert(extendOrders);
                    if(i>0){
                        cartMapper.deleteById(cart.getCartId());
                    }
                }
            }
        }
        if(i>0){
            return extendOrders.getOrdersId().toString();
        }else {
            return "插入失败";
        }
    }

    @Override
    public OrderReturn sellerGetOrderList(SearchOrder searchOrder,String token) {
        Map<String,String> sellerMap=sellerTokenUtil.parseToken(token);
        String sellerId=sellerMap.get("sellerId");
        int page=searchOrder.getPage();
        int limit=searchOrder.getLimit();
        String buyerId=searchOrder.getBuyerId();
        int pageNo=(page-1)*limit;
        int total=orderMapper.sellerGetOrderListCounts(sellerId,"admin").size();
        List<Orders> ordersList;
        if(buyerId.equals("")){
            ordersList= orderMapper.sellerGetOrderList(pageNo,limit,sellerId,"admin");
        }else{
            ordersList= orderMapper.getOrderList(buyerId,pageNo,limit,sellerId,"admin");
            total=orderMapper.getOrderListCount(buyerId,sellerId,"admin").size();
        }
        for(Orders o:ordersList){
            o.getWares().setPictureList(o.getWares().getWaresPicture().split(";"));
        }
        return new OrderReturn(ordersList,total);
    }

    @Override
    public String sellerUpdateOrderState(Integer orderId) {
        Orders order=orderMapper.selectById(orderId);
        Wares wares=waresMapper.selectById(order.getWaresId());
        if(wares.getWaresNumber()<order.getWaresNumber()&&order.getOrderState()<6){
            return "库存不足";
        }
        if(order.getOrderState()<7){
            order.setOrderState(order.getOrderState()+1);
            int i = orderMapper.updateById(order);
            if(i>0){
                //提交历史记录和修改商品状态
                if(order.getOrderState()==7){

                    if(wares.getWaresState()==2){
                        wares.setWaresState(3);
                        waresMapper.updateById(wares);
                        return "商品下架";
                    }
                    //修改商品状态和数量
                }else if(order.getOrderState()==6){
                    if(wares.getWaresNumber().equals(order.getWaresNumber())){
                        wares.setWaresNumber(0);
                        wares.setWaresState(2);
                        Cart cart =cartMapper.selectCartByWaresId(wares.getWaresId());
                        if(cart!=null){
                            cart.setWaresNumber(0);
                            cartMapper.updateById(cart);
                        }
                        waresMapper.updateById(wares);
                        return "商品冻结";
                    }else{
                        wares.setWaresNumber(wares.getWaresNumber()-order.getWaresNumber());
                        Cart cart =cartMapper.selectCartByWaresId(wares.getWaresId());
                        if(cart!=null){
                            if(cart.getWaresNumber()>wares.getWaresNumber()-order.getWaresNumber()) {
                                cart.setWaresNumber(wares.getWaresNumber() - order.getWaresNumber());
                                cartMapper.updateById(cart);
                            }
                        }
                        waresMapper.updateById(wares);
                        return "商品数量减少";
                    }
                }
                return "修改成功";
            }else{
                return "修改失败";
            }
        }else{
            Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            HistoryOrder historyOrder=new HistoryOrder();
            historyOrder.setBuyerId(order.getBuyerId());
            historyOrder.setHistoryOrderState(1);
            historyOrder.setWaresId(order.getWaresId());
            historyOrder.setSellerId(order.getSellerId());
            historyOrder.setWaresNumber(order.getWaresNumber());
            historyOrder.setFinishTime(formatter.format(date));
            historyOrderMapper.insert(historyOrder);
            orderMapper.deleteById(orderId);
            return "订单提交到历史记录";
        }
    }

    @Override
    public String sellerUpdateOrderStateAndDistribution(Integer orderId, String distribution) {
        Orders order=orderMapper.selectById(orderId);
        order.setDistribution(distribution);
        orderMapper.updateById(order);
        return sellerUpdateOrderState(orderId);
    }

    @Override
    public String sellerDeleteOrder(Integer orderId) {
        Orders order=orderMapper.selectById(orderId);
        Wares wares=waresMapper.selectById(order.getWaresId());
        if(order.getOrderState()<=6){
            int i=orderMapper.deleteById(orderId);
            if(i>0){
                //返回商品
                if(order.getOrderState()==6){
                    wares.setWaresNumber(wares.getWaresNumber()+order.getWaresNumber());
                    //撤回状态
                    if(wares.getWaresState()==2){
                        wares.setWaresState(1);
                    }
                    waresMapper.updateById(wares);
                }
                Date date = new Date();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                HistoryOrder historyOrder=new HistoryOrder();
                historyOrder.setBuyerId(order.getBuyerId());
                historyOrder.setHistoryOrderState(2);
                historyOrder.setSellerId(order.getSellerId());
                historyOrder.setWaresId(order.getWaresId());
                historyOrder.setWaresNumber(order.getWaresNumber());
                historyOrder.setFinishTime(formatter.format(date));
                historyOrderMapper.insert(historyOrder);
                return "取消成功";
            }else{
                return "取消失败";
            }
        }else{
            return "无法取消";
        }
    }

}
